package cn.b.sky.flowable.controller;

import cn.b.sky.flowable.enums.FlowNodeUserEnum;
import cn.b.sky.flowable.model.FlowNode;
import cn.b.sky.flowable.model.FlowNodeUser;
import cn.b.sky.flowable.service.FlowNodeService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.form.service.ScreenService;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.impl.bpmn.parser.BpmnParse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/flowNode/*")
public class FlowNodeController extends SecurityController {

  @Resource
  private FlowNodeService flowNodeService;

  @Resource
  private ScreenService screenService;

  @RequestMapping("grantFlowNodeUser")
  public String grantFlowNodeUser(Model model, String modelId, String activitId) {
    if (StringUtils.isBlank(modelId) || StringUtils.isBlank(activitId)) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    FlowNode flowNode = flowNodeService.getFlowNodeByModeIdAndActivitId(modelId, activitId, this.getSiteCode());
    String formKey = flowNode.getFormKey();
    if (!StringUtils.isBlank(formKey) && formKey.indexOf("/") == -1) {
      flowNode.setFormText(screenService.getScreenText(this.getSiteCode(), flowNode.getFormKey()));
    }
    if (flowNode != null) {
      flowNode.setUsers(flowNodeService.getFlowNodeUserByFlowNode(flowNode));
      flowNode.setListeners(flowNodeService.getFlowNodeEventByFlowNode(flowNode));
      model.addAttribute("flowNode", flowNode);
    }
    return "engine/flownode/grantUserInfo";
  }

  @RequestMapping("reloadFlowNodeUser")
  public String reloadFlowNodeUser(Model model, String flowNodeId) {
    if (StringUtils.isBlank(flowNodeId)) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    FlowNode flowNode = flowNodeService.getFlowNodeByFlowNodeId(Long.valueOf(flowNodeId));
    String formKey = flowNode.getFormKey();
    if (!StringUtils.isBlank(formKey) && formKey.indexOf("/") == -1) {
      flowNode.setFormText(screenService.getScreenText(this.getSiteCode(), flowNode.getFormKey()));
    }
    if (flowNode != null) {
      flowNode.setUsers(flowNodeService.getFlowNodeUserByFlowNode(flowNode));
      flowNode.setListeners(flowNodeService.getFlowNodeEventByFlowNode(flowNode));
      model.addAttribute("flowNode", flowNode);
    }
    model.addAttribute("flowNodeId", flowNodeId);
    //flowNode_NotOnly.M
    return "engine/flownode/grantUserInfo";
  }

  /**
   * 
   * <strong>Title : getFlowNodeUser<br></strong>
   * <strong>Description : </strong>异步获取节点配置信息<br> 
   * <strong>Create on : 2016-12-20 下午4:33:48<br></strong>
   * <p>
   * @param model
   * @param flowNodeId
   * @return
   * DWZResult
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("getFlowNodeUser")
  @ResponseBody
  public DWZResult getFlowNodeUser(Model model, String flowNodeId) {
    if(StringUtils.isBlank(flowNodeId)){
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    
    FlowNode flowNode = flowNodeService.getFlowNodeByFlowNodeId(Long.valueOf(flowNodeId));
    if (flowNode != null) {
      return ajaxDone(flowNodeService.getFlowNodeUserByFlowNode(flowNode));
    }
    return ajaxDone(null);
  }
  
  @RequestMapping("addFlowNodeUser")
  public String addFlowNodeUser(Model model) {
    model.addAttribute("flowNodeUserType", FlowNodeUserEnum.getValues());
    return "engine/flownode/addFlowNodeUser";
  }
  @RequestMapping("saveFlowNodeUser")
  @ResponseBody
  public DWZResult saveFlowNodeUser(String users, String roles, String orgs, String isStartor, String formKey,
      String flowNodeId) {
    if (StringUtils.isBlank(flowNodeId)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    List<FlowNodeUser> flowNodeUsers = new ArrayList<FlowNodeUser>();
    StringBuilder candidateGroups = new StringBuilder();
    //角色标识 ROLE:roleCode 用来区分唯一性,组织标识用ORG:code
    if (!StringUtils.isBlank(roles)) {
      //不是表达式
      for (String role : roles.split(",")) {
        candidateGroups.append(SystemConstant.USER_ROLE);
        candidateGroups.append(role);
        candidateGroups.append(",");
      }
    }
    if (!StringUtils.isBlank(orgs)) {
      for (String org : orgs.split(",")) {
        candidateGroups.append(SystemConstant.USER_ORG);
        candidateGroups.append(org);
        candidateGroups.append(",");
      }
    }
    //存在组织
    if (candidateGroups.length() > 0) {
      FlowNodeUser flowNodeUser = new FlowNodeUser();
      flowNodeUser.setFlowNodeId(Long.valueOf(flowNodeId));
      flowNodeUser.setValue(candidateGroups.toString().endsWith(",") ? candidateGroups.substring(0,
          candidateGroups.length() - 1) : candidateGroups.toString());
      flowNodeUser.setType(FlowNodeUserEnum.CANDIDATEGROUPS.getCode());
      flowNodeUser.setStatus(0);
      flowNodeUsers.add(flowNodeUser);
    }
    //初始化users
    if(users == null){
      users = "";
    }
    if (!StringUtils.isBlank(users)) {
      FlowNodeUser user = new FlowNodeUser();
      user.setFlowNodeId(Long.valueOf(flowNodeId));
      user.setValue(users);
      //配置不支持ASSIGNEE类型
      user.setType(FlowNodeUserEnum.CANDIDATEUSERS.getCode());
      user.setStatus(0);
      flowNodeUsers.add(user);
    }
    //流程发起人
    if(!StringUtils.isBlank(isStartor) && "1".equals(isStartor)){
      FlowNodeUser user = new FlowNodeUser();
      user.setFlowNodeId(Long.valueOf(flowNodeId));
      user.setValue(BpmnParse.PROPERTYNAME_INITIATOR_VARIABLE_NAME);
      //配置不支持ASSIGNEE类型
      user.setType(FlowNodeUserEnum.CANDIDATEUSERS.getCode());
      user.setStatus(0);
      flowNodeUsers.add(user);
    }
    flowNodeService.batchSaveFlowNodeUser(flowNodeUsers, formKey, flowNodeId);
   
    return ajaxDone(flowNodeUsers);
  }

  @RequestMapping("delFlowNodeUser")
  @ResponseBody
  public DWZResult delFlowNodeUser(Long id) {
    if (id != null) {
      flowNodeService.deleteFlowNodeUserById(id);
      return ajaxDone(null);
    } else {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
  }
}
